package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
/**
 * @author 剑落萧瑟不自知
 * @Time 2024/4/2
 * @OverView
 */
@Service
@Slf4j
public class FileUploadServiceimpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //业务校验-首先验证上传文件是否为图片
            BufferedImage ImageVerification = ImageIO.read(file.getInputStream());
            if (ImageVerification==null){
                throw new GuiguException(400,"图片格式非法");
            }
            //设置最大图片大小
            int MaxImages = 960*960;
            //进行图片大小的验证
            if (ImageVerification.getWidth()>MaxImages){
                throw new GuiguException(401,"图片大小错误");
            }
            //调用minio客户端进行图片的保存
            //图片的文件名称设置：字符串拼接：时间+UUID.后缀
            //获取当前时间（hutool工具包）
            String today= DateUtil.today();
            //获取文件扩展名
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            //拼接文件名称
            String imageFileName = "/"+today+"/"+ IdUtil.randomUUID()+"."+extName;
            //设置文件的参数
            String bucketName = minioConstantProperties.getBucketName();
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName)
                            .object(imageFileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //发送成功后，返回文件的在线地址
            //拼接文件的在线地址
            String endpointUrl = minioConstantProperties.getEndpointUrl();
            return endpointUrl+"/"+bucketName+imageFileName;
        } catch (Exception e) {
            log.error("[专辑信息]:文件上传接口异常!");
            throw new RuntimeException("文件上传接口异常!"+e);
        }
    }
}
  